﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Jemgine.MapEditor.Operations
{
	internal class NewLine : Operation
	{
        Data.Line CopyPropertiesFrom;
        Engine.Selection Selected;
        Engine.Selection ItemAdded;
        Vector2? A = null;
        Vector2? B = null;

        internal NewLine(Engine.Selection Selected)
		{
			this.Selected = Selected;
		}

        internal NewLine(Data.Line CopyFrom, Engine.Selection Selected, Vector2 A, Vector2 B)
        {
            this.CopyPropertiesFrom = CopyFrom;
            this.Selected = Selected;
            this.A = A;
            this.B = B;
        }

		internal override ReturnCode Do(EditorState ES)
		{
            Data.EntityRecord Entity = ES.GetTopObject(Selected) as Data.EntityRecord;
            if (Entity == null) return ReturnCode.DoNotAddToUndoStack;

			Data.Line NewSpline = CopyPropertiesFrom == null ? new Data.Line() : new Data.Line(CopyPropertiesFrom);
            if (A == null)
            {
                NewSpline[0].Position = Entity.TransformToLocalSpace(ES.RawMousePosition);
                NewSpline[1].Position = Entity.TransformToLocalSpace(ES.RawMousePosition + new Vector2(4, 0));
            }
            else
            {
                NewSpline[0].Position = (Vector2)A;
                NewSpline[1].Position = (Vector2)B;
            }
            Entity.AttachedElements.Add(NewSpline);

            ItemAdded = new Engine.Selection(Engine.Selection.Types.EntityElement, Selected.TopIndex,
				Entity.AttachedElements.Count - 1, 0);
            ES.RebuildNode(ItemAdded.TopIndex);

            if (A == null)
                ES.SelectItem(ItemAdded);
            else
                ES.SelectItem(new Engine.Selection(Engine.Selection.Types.Vertex, ItemAdded.TopIndex, ItemAdded.MiddleIndex, 1));

			return ReturnCode.AddToUndoStack;
		}

		internal override void Undo(EditorState ES)
		{
			(ES.Map.Elements[ItemAdded.TopIndex] as Data.EntityRecord).AttachedElements.RemoveAt(ItemAdded.MiddleIndex);
            ES.RebuildNode(ItemAdded.TopIndex);
            ES.SelectItem(new Engine.Selection(Engine.Selection.Types.MapElement, ItemAdded.TopIndex, 0, 0));
		}
	}
}
